package com.itheima.service.impl;

import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.*;

/**
 * 预约设置服务实现类
 */
@Service
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingMapper orderSettingMapper;

    @Override
    public void importOrderSettings(MultipartFile excelFile) {


        try (InputStream inputStream = excelFile.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            List<OrderSetting> orderSettings = new ArrayList<>();
            //添加空列表检查
            if (orderSettings == null || orderSettings.isEmpty()) {
                throw new IllegalArgumentException("Excel文件中没有数据");
            }


            //从第二行开始读取数据
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }

                OrderSetting orderSetting = new OrderSetting();

                //假设Excel第一列是日期，第二列是可预约人数
                Cell dateCell = row.getCell(0);
                Cell numberCell = row.getCell(1);

                //解析日期
                if (dateCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                    orderSetting.setOrderDate(dateCell.getDateCellValue());
                } else {
                    throw new Exception("第" + (i + 1) + "行日期格式不正确");
                }

                //解析可预约人数
                if (numberCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                    orderSetting.setNumber((int) numberCell.getNumericCellValue());
                } else {
                    throw new Exception("第" + (i + 1) + "行可预约人数格式不正确");
                }

                orderSettings.add(orderSetting);
            }

            //批量保存到数据库
            orderSettingMapper.batchAdd(orderSettings);
        } catch (Exception e) {
            try {
                throw new Exception("解析Excel文件失败: " + e.getMessage());
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    /**
     * 根据日期修改可预约人数
     *
     * @param orderSetting
     */
    @Override
    @Transactional
    public void editNumberByOrderDate(OrderSetting orderSetting) {
        if (orderSetting == null || orderSetting.getOrderDate() == null || orderSetting.getNumber() == null) {
            throw new IllegalArgumentException("参数不完整");
        }

        if (orderSetting.getNumber() < 0) {
            throw new IllegalArgumentException("可预约人数不能为负数");
        }

        //检查该日期是否已有设置
        OrderSetting existing = orderSettingMapper.findByDate(orderSetting.getOrderDate());

        if (existing != null) {
            //更新已有设置
            existing.setNumber(orderSetting.getNumber());
            orderSettingMapper.updateNumberByDate(existing);
        } else {
            //新增设置
            OrderSetting newSetting = new OrderSetting();
            newSetting.setOrderDate(orderSetting.getOrderDate());
            newSetting.setNumber(orderSetting.getNumber());
            newSetting.setReservations(0); //初始已预约人数为0
            orderSettingMapper.insert(newSetting);
        }
    }

    /**
     * 根据年月查询对应的预约设置信息
     *
     * @param month
     * @return
     */
    @Override
    public List<OrderSetting> getOrderSettingByMonth(String month) {
        //参数校验
        if (month == null || month.trim().isEmpty()) {
            throw new IllegalArgumentException("月份参数不能为空");
        }

        //解析月份
        String[] parts = month.split("-");
        if (parts.length != 2) {
            throw new IllegalArgumentException("月份格式不正确，应为YYYY-MM");
        }

        int year, monthValue;
        try {
            year = Integer.parseInt(parts[0]);
            monthValue = Integer.parseInt(parts[1]);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("月份参数必须为数字");
        }

        //计算该月的开始日期和结束日期
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, monthValue - 1, 1);
        Date beginDate = calendar.getTime();

        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date endDate = calendar.getTime();

        //查询数据库
        List<OrderSetting> orderSettings = orderSettingMapper.getOrderSettingByMonth(beginDate, endDate);

        return orderSettings;
    }
}
